<template>
  <view class="all" :style="{ opacity: curPage === 'map' ? '0' : '1'}">
    <uni-nav-bar title="创建我的车友团" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
    <image :src="CreateImg" mode="widthFix" class="New_top"></image>
    <view class="New_team" style="border-bottom: 1px solid #eee;">
      <text class="New_text">团名</text>
      <input type="text" placeholder="请输入团名" v-model="taemName" maxlength="16" />
    </view>
    <view class="New_team center" style="border-bottom: 1px solid #eee;">
      <text class="New_text">团坐标</text>
      <view style="width: 400rpx;margin:0px 20rpx">{{locName?locName:'请选择地址'}}</view>
      <view class="column" @click="chooseLocation">
        <image src="../../static/icon/positions.svg" mode="" style="width: 36rpx;height: 36rpx;"></image>
        <text style="font-size: 20rpx;color:#1B91FF;margin-top:5rpx;">已选位置</text>
      </view>
    </view>
    <view class="New_team">
      <text class="New_text">团助理</text>
      <view class="New_List">
        <view class="New_item" v-for="(item, index) in AssistantList" :key="index"
          @click="item.status != 1 ? '' : changeAss(item.id)">
          <image :src="item.image" mode="" :style="{ border: admin_id != item.id ? 'none' : '2px solid #007AFF' }">
          </image>
          <text>{{ item.name }}</text>
          <text v-if="item.status != 1">繁忙中</text>
          <text></text>
        </view>
      </view>
    </view>
    <view class="New_buttom" @click="submit()">开团</view>
  </view>
  <!-- 选择地址列表 -->
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import * as AMapLoader from '@amap/amap-jsapi-loader';
  import { ref, Ref } from 'vue';
  import { navBack } from '@/utils/navigator';
  import { toPublish } from '@mqtt';
  import { showLoading,successToast, errorToast } from '@/utils/prompt';
  import { Assistant, Creategroup } from '@/gql/team';
  import Lotlats from '@c/team/Lotlat.vue';
  import { getDriverID } from '@/stores/driverID';
  const driver_id = getDriverID();
  const AssistantList = ref([]);
  const admin_id = ref(''); //助理ID
  const taemName = ref('');
  const CreateImg = ref('');
  const repeat = ref(true); //放重复点击
  // data
  const curPage : Ref<'form' | 'map'> = ref('form');
  const longitude = ref()
  const latitude = ref()
  const mapURI = ref('');
  const locName = ref('')

  /**
   * 获取助理列表
   */
  Assistants();
  function Assistants() {
    showLoading('正在加载');
    const payload = {
      query: Assistant,
    };
    toPublish('ql/team/getAdmin', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      AssistantList.value = data.admin_list;
    });
  }
  /**
   * 获取当前城市信息
   * @param  lat 当前位置的纬度
   * @param  lot 当前位置的经度
   * @return MapPage 修改地图页面的first状态
   */
  function position(lat : number, lot : number) {
    console.log(JSON.stringify(lat) + '*****')
    longitude.value = lot;
    latitude.value = lat;
    getPositionByLonLats(lot, lat)
  }
  function getPositionByLonLats(lng : number, lat : number) {
    AMapLoader.load({
      key: '28c93d7518383bfa130b6c7cd239c331', // 申请好的Web端开发者Key，首次调用 load 时必填  
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Geocoder', 'AMap.Geolocation'] //插件列表
    })
      .then(AMap => {
        const lnglat = [lng, lat]
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress(lnglat, function (status, result) {
          console.log(status+'*****'+result.regeocode)
          if (status === 'complete' && result.regeocode) {
            locName.value = result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
        })
      })
      .catch(e => {
        console.log(e + '*******')
      })

  }
  /**
   * 跳转到地址列表 选择位置信息
   */
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude.value},${longitude.value}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        console.log(JSON.stringify(loc) + '*****')
        curPage.value = 'form';
        longitude.value = loc.latlng.lng;
        latitude.value = loc.latlng.lat;
        locName.value = loc.poiname
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.removeEventListener('message', msgListener);
      }
    }
    window.addEventListener('message', msgListener, false);
  }
  /**
   * @param {Object} id 团助理的iD
   */
  function changeAss(id) {
    admin_id.value = id;
  }
  /**
   * 提交并确定创建团
   */
  function submit() {
    if (!taemName.value) {
      errorToast('请输入团名');
      return;
    }
    if (!locName.value) {
      errorToast('请选择团位置信息');
      return;
    }
    if (!admin_id.value) {
      errorToast('请选择团助理');
      return;
    }
    showLoading()
    if (!repeat.value) {
      return;
    }
    repeat.value = false;
    const payload = {
      admin_id: admin_id.value,
      driver_id,
      name: taemName.value,
      longitude:longitude.value,
      latitude:latitude.value,
      address:locName.value
    };
    toPublish('team/createTeam', payload, (obj : any) => {
      uni.hideLoading();
      const { code, msg } = obj;
      if (code === 1) {
        successToast(msg);
        uni.setStorageSync('type', 'team');
        setTimeout(() => {
          navBack();
        }, 1000);
      } else {
        repeat.value = true;
        errorToast(msg);
      }
    });
  }
  Creategroups();
  /**
   * 获取创建团的顶部图片
   */
  function Creategroups() {
    const payload = {
      query: Creategroup,
      variables: { type: 'team-create' },
    };
    toPublish('ql/team/getAds', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      CreateImg.value = data.get_ads.imageurl;
    });
  }
</script>

<style scoped lang="less">
  @import url('../team/less/newTeam.less');
</style>